package com.leetcode.leetcode1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *  四数之和
 * @author: luhd
 * @create: 2021-08-31
 */
public class Practice18 {
    public static void main(String[] args) {
        int[] nums = {2,2,2,2,2};
        int target = 8;
        List<List<Integer>> lists = fourSum(nums, target);
        System.out.println(lists);
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        int len = nums.length;
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        if(nums==null ||len<4) return lists;
        Arrays.sort(nums);
        for (int i = 0; i < len-3; i++) {
            /*if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }
            if (nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target) {
                continue;
            }*/

            for (int j = i+1; j < len-2; j++) {
                /*if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if (nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target) {
                    continue;
                }*/

                int left = j+1;
                int right = len-1;
                while(left<right){
                    int sum = nums[i]+nums[j]+nums[left]+nums[right];
                    if(sum == target){
                        //lists.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        List<Integer> res = new ArrayList<>();
                        res.add(nums[i]);
                        res.add(nums[j]);
                        res.add(nums[left]);
                        res.add(nums[right]);
                        Collections.sort(res);
                        if(!lists.contains(res)) lists.add(res);
                        left++;
                        right--;
                        /*while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        left++;
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        right--;*/
                    }
                    else if(sum<target) left++;
                    else if(sum>target) right--;
                }
            }
        }
        return lists;
    }
}
